﻿# -*- coding: utf-8 -*-
import cgi
import datetime
import wsgiref.handlers
import os

from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext.webapp.util import run_wsgi_app

import simplejson
from google.appengine.api import memcache
import re
import time

class Handmemo(db.Model):
	user = db.StringProperty(multiline=False)
	memo = db.TextProperty()
	time = db.DateTimeProperty(auto_now=True)

def ismobile(self):
	if memcache.get('mobile'):
		return memcache.get('mobile')
	else:
		user_agent = self.request.headers['User-Agent']
		if (re.search('iPod|iPhone|Android|Opera Mini|BlackBerry|webOS|UCWEB|Blazer|PSP|Symbian|IEMobile', user_agent)):
			return True
		else:
			return None

def welcome(self):
	template_values = {
		'loginurl': users.create_login_url(self.request.uri)
	}
	if ismobile(self):
		path = os.path.join(os.path.dirname(__file__), 'template/mobile/welcome.html')
	else:
		path = os.path.join(os.path.dirname(__file__), 'template/desktop/welcome.html')
	self.response.out.write(template.render(path, template_values))

def redirect(self):
	if ismobile(self):
		self.redirect('/m')
	else:
		self.redirect('/')


class AddMemo(webapp.RequestHandler):
	def post(self):
		user = users.get_current_user()
		
		if user:
			handmemo = Handmemo()
			handmemo.user = user.email()
			handmemo.memo = self.request.get('memo')
			handmemo.put()
			returndata = simplejson.dumps({'key':str(handmemo.key()),'time':str(handmemo.time)})
			redirect(self)
		else:
			welcome(self)


class DeleteMemo(webapp.RequestHandler):
	def post(self):
		user = users.get_current_user()
		
		if user:
			key = self.request.get('key')
			if key:
				handmemo = Handmemo.get(db.Key(key))
				if handmemo:
					Handmemo.delete(handmemo)
			redirect(self)
		else:
			welcome(self)


class UpdateMemo(webapp.RequestHandler):
	def post(self):
		user = users.get_current_user()
		
		if user:
			key = self.request.get('key')
			if key:
				handmemo = Handmemo.get(db.Key(key))
				if not handmemo:
					handmemo = Handmemo()
				handmemo.memo = self.request.get('memo')
				handmemo.put()
				returndata = simplejson.dumps({'time':str(handmemo.time)})
			redirect(self)
		else:
			welcome(self)


class ViewMemo(webapp.RequestHandler):
	def get(self):
		user = users.get_current_user()
		
		if user:
			key = self.request.get('key')
			if key:
				handmemo = Handmemo.get(db.Key(key))
				if handmemo:
					template_values = {
						'user': user.email(),
						'logout': users.create_logout_url(self.request.uri),
						'handmemo': handmemo
					}
					if ismobile(self):
						path = os.path.join(os.path.dirname(__file__), 'template/mobile/viewmemo.html')
					else:
						path = os.path.join(os.path.dirname(__file__), 'template/desktop/viewmemo.html')
					self.response.out.write(template.render(path, template_values))
			else:
				redirect(self)
		else:
			welcome(self)


class EditMemo(webapp.RequestHandler):
	def get(self):
		user = users.get_current_user()
		
		if user:
			key = self.request.get('key')
			if key:
				handmemo = Handmemo.get(db.Key(key))
				if handmemo:
					template_values = {
						'user': user.email(),
						'logout': users.create_logout_url(self.request.uri),
						'handmemo': handmemo
					}
					if ismobile(self):
						path = os.path.join(os.path.dirname(__file__), 'template/mobile/editmemo.html')
					else:
						path = os.path.join(os.path.dirname(__file__), 'template/desktop/editmemo.html')
					self.response.out.write(template.render(path, template_values))
			else:
				redirect(self)
		else:
			welcome(self)


class MainPage(webapp.RequestHandler):
	def get(self):
		memcache.delete("mobile")
		user = users.get_current_user()

		if user:
			n = self.request.get('n')
			if n and n.isdigit():
				n = int(n)
			else:
				n = 100
			k = self.request.get('k')
			if k:
				starttime = Handmemo.get(db.Key(k)).time
				if starttime:
					query = Handmemo.gql('WHERE user = :user and time <= :time ORDER BY time DESC', user = user.email(), time = starttime)
			else:
				query = Handmemo.gql('WHERE user = :user ORDER BY time DESC', user = user.email())
			handmemos = query.fetch(n+1)

			if len(handmemos) == n+1:
				k = handmemos[-1].key()
				handmemos = handmemos[:n]
			else:
				k = None
			
			template_values = {
				'user': user.email(),
				'logout': users.create_logout_url(self.request.uri),
				'handmemos': handmemos,
				'k': k
			}
			if ismobile(self):
				path = os.path.join(os.path.dirname(__file__), 'template/mobile/handmemo.html')
			else:
				path = os.path.join(os.path.dirname(__file__), 'template/desktop/handmemo.html')
			self.response.out.write(template.render(path, template_values))
		else:
			welcome(self)


class MobilePage(webapp.RequestHandler):
	def get(self):
		memcache.set('mobile',True)
		user = users.get_current_user()
		
		if user:
			n = self.request.get('n')
			if n and n.isdigit():
				n = int(n)
			else:
				n = 100
			k = self.request.get('k')
			if k:
				starttime = Handmemo.get(db.Key(k)).time
				if starttime:
					query = Handmemo.gql('WHERE user = :user and time <= :time ORDER BY time DESC', user = user.email(), time = starttime)
			else:
				query = Handmemo.gql('WHERE user = :user ORDER BY time DESC', user = user.email())
			handmemos = query.fetch(n+1)

			if len(handmemos) == n+1:
				k = handmemos[-1].key()
				handmemos = handmemos[:n]
			else:
				k = None
			
			template_values = {
				'user': user.email(),
				'logout': users.create_logout_url(self.request.uri),
				'handmemos': handmemos,
				'k': k
			}
			path = os.path.join(os.path.dirname(__file__), 'template/mobile/handmemo.html')
			self.response.out.write(template.render(path, template_values))
		else:
			welcome(self)


class GetMemo(webapp.RequestHandler):
	def get(self):
		user = users.get_current_user()
		
		if user:
			n = self.request.get('n')
			if n and n.isdigit():
				n = int(n)
			else:
				n = 100
			k = self.request.get('k')
			if k:
				starttime = Handmemo.get(db.Key(k)).time
				if starttime:
					query = Handmemo.gql('WHERE user = :user and time <= :time ORDER BY time DESC', user = user.email(), time = starttime)
			else:
				query = Handmemo.gql('WHERE user = :user ORDER BY time DESC', user = user.email())
			handmemos = query.fetch(n+1)

			if len(handmemos) == n+1:
				k = handmemos[-1].key()
				handmemos = handmemos[:n]
			else:
				next = None
				
			json = '{"user": {"email": "' + str(user.email()) + '", "nickname": "' + str(user.nickname()) + '"}, "handmemos": ['
			for i in range(len(handmemos)):
				handmemo = handmemos[i]
				if i == 0:
					json += '{"memo": "' + str(cgi.escape(handmemo.memo).encode('utf-8')) + '", "time": "' + str(handmemo.time) + '", "key": "' + str(handmemo.key()) +'"}'
				else:
					json += ', {"memo": "' + str(cgi.escape(handmemo.memo).encode('utf-8')) + '", "time": "' + str(handmemo.time) + '", "key": "' + str(handmemo.key()) +'"}'
			json += '], "k": "' + str(k) + '"}'

			self.response.out.write(json)
		else:
			return None


application = webapp.WSGIApplication([
	('/add', AddMemo),
	('/delete', DeleteMemo),
	('/update', UpdateMemo),
	('/view', ViewMemo),
	('/edit', EditMemo),
	('/', MainPage),
	('/m', MobilePage),
	('/get', GetMemo)
], debug=True)


def main():
	wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
	main()